package me.minetsh.imaging.view.stick;

import ohos.agp.components.Component;
import ohos.agp.utils.Matrix;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;

/**
 * Created by felix on 2017/11/15 下午5:44.
 */
public class IMGStickerAdjustHelper implements Component.TouchEventListener {

    private static final String TAG = "IMGStickerAdjustHelper";

    private Component mView;

    private IMGStickerView mContainer;

    private float mCenterX, mCenterY;

    private double mRadius, mDegrees;

    private Matrix M = new Matrix();

    /**
     * 构造函数
     *
     * @param container 父容器
     * @param view 视图
     */
    public IMGStickerAdjustHelper(IMGStickerView container, Component view) {
        mView = view;
        mContainer = container;
        mView.setTouchEventListener(this);
    }

    @Override
    public boolean onTouchEvent(Component component, TouchEvent event) {
        MmiPoint point = event.getPointerPosition(event.getIndex());
        switch (event.getAction()) {
            case TouchEvent.PRIMARY_POINT_DOWN:

                float x = point.getX();

                float y = point.getY();

                mCenterX = mCenterY = 0;

                float pointX = mView.getContentPositionX() + x - mContainer.getPivotX();

                float pointY = mView.getContentPositionY() + y - mContainer.getPivotY();

                mRadius = toLength(0, 0, pointX, pointY);

                mDegrees = toDegrees(pointY, pointX);

                M.setTranslate(pointX - x, pointY - y);

                M.postRotate((float) -toDegrees(pointY, pointX), mCenterX, mCenterY);

                return true;

            case TouchEvent.POINT_MOVE:

                float[] xy = {point.getX(), point.getY()};

                pointX = mView.getContentPositionX() + xy[0] - mContainer.getPivotX();

                pointY = mView.getContentPositionY() + xy[1] - mContainer.getPivotY();

                double radius = toLength(0, 0, pointX, pointY);

                double degrees = toDegrees(pointY, pointX);

                float scale = (float) (radius / mRadius);

                mContainer.addScaleValue(scale);

                mContainer.setRotation((float) (mContainer.getRotation() + degrees - mDegrees));

                mRadius = radius;

                return true;
        }
        return false;
    }

    private static double toDegrees(float v, float v1) {
        return Math.toDegrees(Math.atan2(v, v1));
    }

    private static double toLength(float x1, float y1, float x2, float y2) {
        return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
    }
}
